import { ViewLoadingService } from './view-loading-service';

/**
 * 部件加载服务类
 *
 * @export
 * @class CtrlLoadingService
 * @extends {LoadingServiceBase}
 */
export class CtrlLoadingService {
  /**
   * 视图loading服务
   *
   * @type {*}
   * @memberof CtrlLoadingService
   */
  viewLoadingService: ViewLoadingService;

  /**
   * 部件加载构造函数。
   * @memberof CtrlLoadingService
   */
  constructor(ViewLoadingService: any) {
    this.viewLoadingService = ViewLoadingService;
  }

  /**
   * 是否加载
   *
   * @type {boolean}
   * @memberof LoadingServiceBase
   */
  isLoading: boolean = false;

  /**
   * 部件dom对象
   *
   * @type {*}
   * @memberof CtrlLoadingService
   */
  selection: any = null;

  /**
   * 部件加载
   *
   * @public
   * @memberof CtrlLoadingService
   */
  beginLoading(controlId: string) {
    this.selection = document.querySelector(`#${controlId}`);
    if (!this.selection || this.isLoading) {
      return;
    }
    this.isLoading = true;
    const loadingEl = document.createElement('ibz-skeleton');
    loadingEl.setAttribute('min-height', '300');
    loadingEl.setAttribute('col', '1');
    loadingEl.setAttribute('line-height', '30');
    loadingEl.setAttribute('header-height', '30');
    loadingEl.setAttribute('footer-height', '30');
    loadingEl.setAttribute('show-header', 'true');
    loadingEl.setAttribute('show-footer', 'true');
    this.selection.appendChild(loadingEl);
    // 开启视图loading
    if (this.viewLoadingService) {
      this.viewLoadingService.beginLoading();
    }
  }

  /**
   * 部件加载2 （根据传入Key获取Dom，进行局部刷新）
   *
   * @public
   * @memberof CtrlLoadingService
   */
  beginLoading2(key: string) {
    this.selection = document.querySelector(key);
    if (!this.selection || this.isLoading) {
      return;
    }
    this.isLoading = true;
    // 自定义loading元素
    const loadingEl = document.createElement('ibz-skeleton');
    loadingEl.setAttribute('min-height', '300');
    loadingEl.setAttribute('col', '1');
    loadingEl.setAttribute('line-height', '30');
    loadingEl.setAttribute('header-height', '30');
    loadingEl.setAttribute('footer-height', '30');
    loadingEl.setAttribute('show-header', 'true');
    loadingEl.setAttribute('show-footer', 'true');
    this.selection.appendChild(loadingEl);
    // 开启视图loading
    if (this.viewLoadingService) {
      this.viewLoadingService.beginLoading();
    }
  }

  /**
   * 加载结束
   *
   * @memberof CtrlLoadingService
   */
  endLoading() {
    if (!this.isLoading) {
      return;
    }
    const lastChild = this.selection?.lastElementChild ? this.selection?.lastElementChild : this.selection?.lastChild;
    if (lastChild && lastChild.tagName === 'ibz-skeleton'.toLocaleUpperCase()) {
      this.selection.removeChild(lastChild);
    }
    this.isLoading = false;
    this.selection = null;
    // 关闭视图loading
    if (this.viewLoadingService) {
      this.viewLoadingService.endLoading();
    }
  }
}
